package com.zhuhjay.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Spring上下文工具类（Spring底层组件的使用）
 * @author ZhuHJay
 * @date 2023/1/12 15:22
 */
@Component
@SuppressWarnings("all")
public final class SpringContextHolder implements ApplicationContextAware {

    /** SpringIoc容器 **/
    private static ApplicationContext applicationContext;

    /** 根据类型获取容器中的bean **/
    public static <T> T getBean(Class<T> requiredType){
        return applicationContext.getBean(requiredType);
    }

    /** 根据beanId获取容器中对应的bean (@SuppressWarnings 警告压制) **/
    public static <T> T getBean(String name){
        return (T) applicationContext.getBean(name);
    }

    /** 根据类型获取容器中该类型的所有bean **/
    public static <T> Map<String, T> getBeansOfType(Class<T> requiredType){
        return applicationContext.getBeansOfType(requiredType);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }
}
